import React, {Component} from 'react';
import { Form, Input, Button, Icon, Modal, Checkbox, message } from 'antd';
import { Link, history } from 'react-router-dom';
// import './index.less';
import axios from 'axios';
const FormItem = Form.Item;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

class Forgetpwd extends Component {
    constructor(props) {
      super(props);
      this.state = {
        confirmDirty: false,
        visible: false,
        autoCompleteResult: [],
        checked: true,
        registerMark: '确认修改',
        getCode: '获取验证码',
        mobile: '',
      }
      this.showModal = this.showModal.bind(this);
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    }
  gotologin = () => {
    window.history.replaceState({}, null, '/')
  }
    handleOk = () => {
        this.setState({visible: false });
    }
    handleCancel = () => {
        this.setState({ visible: false });
    }
    handleOkCopy = () => {
        this.setState({visibleCopy: false });
    }
    handleCancelCopy = () => {
        this.setState({ visibleCopy: false });
    }
    modalCopy = () =>{
        this.setState({ visibleCopy: true });
    }
    onChange = (e) => {
      // console.log('checked = ', e.target.checked);
      this.setState({
          checked: e.target.checked,
      });
    }
    handleSubmit = (e) => {
      e.preventDefault();
      const _this = this;
      const Token = localStorage.getItem("token");
      const telPhone = this.state.mobile;
      // const regExp = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/;
      this.props.form.validateFieldsAndScroll((err, values) => {
        // console.log(values);
        if (!err) {
              _this.viodClickAgain();
              setTimeout(()=>{
                _this.setState({
                    registerMark: '确认修改'
                })
              },2000)
              const valuesData = {
                telPhone: telPhone,
                password: values.password,
                attr1: values.attr1,
                username: values.username
              }
            
              axios({
                method: 'post',
                url: '/api/customer/user/forgetPass',
                data: valuesData,
                headers: {
                  'Content-Type': 'application/json',
                  Authorization:Token,
                }
              })
              .then(function(response){
                  if(response.data.status == "false"){
                      message.warning(response.data.message);
                      return false;
                  }else if(response.data.message == '恭喜您已经成功修改密码！') {
                      setTimeout(()=>{
                        message.success(response.data.message);
                      },2000);
                      setTimeout(()=>{
                        window.history.replaceState({}, null, '/')
                        _this.props.history.push('/');
                      },4000)
                  }
              })
              .catch(function(error){
                  console.log(error);
              });
            }else {
                console.log('Received values of form: ', values);
            }
          // this.SubmitPost(values)
      });
    }

    handleConfirmBlur = (e) => {
      const value = e.target.value;
      this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    }
    compareToFirstPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('您输入的两个密码不一致');
      } else {
        callback();
      }
    }
    validateToNextPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && this.state.confirmDirty) {
        form.validateFields(['confirm'], { force: true });
      }
      callback();
    }

    viodClickAgain=()=>{
      this.setState({
          registerMark: '提交中...'
      })
    }


    handleCode =()=>{
      const _this = this;
      let sec = 60;
      const mobile = this.state.mobile;
      const Token = localStorage.getItem("token");
      const myreg = /^1[0-9]{10}$/;  
      if (!myreg.test(mobile)) {
        message.warning('请输入正确的手机号')
      }else if(this.state.getCode !== '获取验证码'){
        return false;
      }else{
        axios({
          method: 'get',
          url: '/api/customer/rest/sendPassMsg?mobile='+ mobile,
          headers: {
            'Content-Type': 'application/json',
            Authorization:Token,
          }
        })
        .then(function(response){
          if(response.data.code == '201'){
            message.warning('请输入正确的手机号');
          }else if(response.data.code == '202'){
            message.warning('获取手机验证码失败');
          }else if(response.data.code == '200') {
            const timer = setInterval(function(){
              sec--;
              if(sec < 0){
                clearInterval(timer);
                _this.setState({
                  getCode:  '获取验证码',
                })
              }else {
                _this.setState({
                  getCode:  sec + 's 后重新获取',
                })
              }
            },1000)
          }
        })
      }
    }

    getMobile =(e)=> {
      const _this = this;
      const Token = localStorage.getItem("token");
      const username = e.target.value;
      axios({
        method: 'post',
        url: '/api/customer/user/getTelbyName',
        data: {
          username: username
        },
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token,
        }
      })
      .then(function(response){
        // console.log(response)
        if(response.data.code == 201){
          message.warning(response.data.message)
        }else if(response.data.code == 200){
          _this.setState({
            mobile: response.data.data
          })
        }
      })
    }

    render() {
      const { getFieldDecorator } = this.props.form;
      const { autoCompleteResult, visible, visibleCopy } = this.state;
      const disabledOrNot = this.state.checked ? 'primary' : 'default';
      const disabled = (this.state.checked) && (this.state.registerMark == '确认修改') ?  '' : 'disabled';
      const getCodeBtn = this.state.getCode !== '获取验证码' ? "disab getCodeBtn" : "getCodeBtn";

      return (
        <div className="registerBox"> 
          <div className="img_bg">
            <div className="logo_bg">
              <a href="https://www.sinochembaas.com/" target="_blank">
                <img src={require("../Login/img/logo.png")} alt="" className="login_logo" />
              </a>  
                <img src={require("../Login/img/bg.png")} alt="" className="login_bg" />
            </div>
          </div>
          <div className="form_r">     
            <Form className="registerForm" onSubmit={this.handleSubmit}>
              <div className="registerCt">
                <h3 className="registerCtTop">忘记密码</h3>                  
                    <FormItem>
                      {getFieldDecorator('username', {
                        rules: [{ required: true, message: '请输入用户名' }],
                      })(
                        <Input size="large" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="请输入用户名" className="signInput" onBlur={this.getMobile} />
                      )}
                  </FormItem>
                    <FormItem>
                        <Input size="large" prefix={<Icon type="phone" style={{ color: 'rgba(0,0,0,.25)' }} />} type="text" disabled value={this.state.mobile} />
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('attr1', {
                      rules: [{ required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/ }],
                    })(
                      <div className="getCodeBox">
                        <Input size="large" prefix={<Icon type="message" style={{ color: 'rgba(0,0,0,.25)' }} />} type="text" placeholder="请输入短信验证码" maxLength={8} />
                        <span className={getCodeBtn} onClick = {this.handleCode}>{this.state.getCode}</span>
                      </div>
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('password', {
                      rules: [{
                        required: true, message: '请输入8到20个字符之间的字母、数字和符号组合密码', pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/
                      }, {
                        validator: this.validateToNextPassword,
                      }],
                    })(
                      <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" maxLength={20} />
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('confirmpassword', {
                      rules: [{
                        required: true, message: '请再次设置新的登录密码',
                      }, {
                        validator: this.compareToFirstPassword,
                      }],
                    })(
                      <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="确认新的登录密码" />
                    )}
                  </FormItem>
                <Button type="primary" size="large" htmlType="submit" type= {disabledOrNot} disabled={disabled} className="registerBtn">{this.state.registerMark}</Button>
                <span className="loginBtn">记起密码？返回<Link to="/"><em onClick={this.gotologin}>登录页面</em></Link></span>
              </div>
            </Form>
          </div>
          </div>
      )
    }
  }
  
  const ForgetPwd = Form.create()(Forgetpwd);
  export default ForgetPwd;